<template>
  <div class="customer-transfer">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客户转移审批</span>
          <el-button type="primary" @click="handleBatchTransfer">批量转移</el-button>
        </div>
      </template>

            <!-- 审批状态统计卡片 -->
      <el-row :gutter="20" class="status-statistics">
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
          <el-card class="status-card pending" shadow="hover">
            <div class="status-card-content">
              <div class="status-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-number">{{ statistics.pending }}</div>
                <div class="status-label">待审批</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
          <el-card class="status-card approved" shadow="hover">
            <div class="status-card-content">
              <div class="status-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-number">{{ statistics.approved }}</div>
                <div class="status-label">已批准</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
          <el-card class="status-card rejected" shadow="hover">
            <div class="status-card-content">
              <div class="status-icon">
                <el-icon><CircleClose /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-number">{{ statistics.rejected }}</div>
                <div class="status-label">已拒绝</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 转移历史趋势图表 -->
      <el-card class="trend-chart-card" v-if="trendData.length > 0">
        <template #header>
          <span>转移趋势分析</span>
        </template>
        <div ref="trendChartRef" style="height: 300px;"></div>
      </el-card>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="客户姓名">
              <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="转移状态">
              <el-select v-model="searchForm.transferStatus" placeholder="请选择转移状态" clearable style="width: 100%">
                <el-option label="待审批" value="pending" />
                <el-option label="已批准" value="approved" />
                <el-option label="已拒绝" value="rejected" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="申请人">
              <el-input v-model="searchForm.applicantName" placeholder="请输入申请人姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="申请时间">
              <el-date-picker
                v-model="searchForm.applyDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 批量操作 -->
      <div class="batch-actions">
        <el-button 
          v-if="canBatchApprove"
          type="success" 
          @click="handleBatchApprove"
          :disabled="selectedRows.length === 0"
          :loading="batchApproveLoading"
        >
          批量批准
        </el-button>
        <el-button 
          v-if="canBatchReject"
          type="danger" 
          @click="handleBatchReject"
          :disabled="selectedRows.length === 0"
          :loading="batchRejectLoading"
        >
          批量拒绝
        </el-button>
        <el-button 
          v-if="canExport"
          @click="handleExport"
          :loading="exportLoading"
        >
          导出记录
        </el-button>
      </div>

      <!-- 转移记录表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :max-height="tableHeight"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="customerName" label="客户姓名" min-width="120" fixed="left" />
        <el-table-column prop="customerPhone" label="客户电话" min-width="120" />
        <el-table-column prop="fromUserName" label="原负责人" min-width="100" />
        <el-table-column prop="toUserName" label="目标负责人" min-width="100" />
        <el-table-column prop="transferStatus" label="转移状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTransferStatusType(row.transferStatus)">
              {{ getTransferStatusLabel(row.transferStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyReason" label="申请原因" min-width="200" show-overflow-tooltip />
        <el-table-column prop="applicantName" label="申请人" min-width="100" />
        <el-table-column prop="applyTime" label="申请时间" width="160" />
        <el-table-column prop="approverName" label="审批人" min-width="100" />
        <el-table-column prop="approveTime" label="审批时间" width="160" />
        <el-table-column prop="approveRemark" label="审批备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <template v-if="row.transferStatus === 'pending'">
              <el-button v-if="canApprove" type="text" @click="handleApprove(row)" style="color: #67c23a">批准</el-button>
              <el-button v-if="canReject" type="text" @click="handleReject(row)" style="color: #f56c6c">拒绝</el-button>
            </template>
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button v-if="canDelete" type="text" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 批量转移对话框 -->
    <el-dialog
      v-model="batchTransferDialog.visible"
      title="批量客户转移"
      width="600px"
    >
      <el-form :model="batchTransferDialog.form" label-width="100px">
        <el-form-item label="选择客户">
          <el-select
            v-model="batchTransferDialog.form.customerIds"
            multiple
            filterable
            remote
            :remote-method="searchCustomers"
            :loading="customerLoading"
            placeholder="请输入客户名称搜索"
            style="width: 100%"
          >
            <el-option
              v-for="customer in customerOptions"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标用户">
          <el-select v-model="batchTransferDialog.form.targetUserId" placeholder="请选择目标用户">
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.userName"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转移说明">
          <el-input
            v-model="batchTransferDialog.form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入转移说明"
          />
        </el-form-item>
        <el-form-item label="需要审批">
          <el-switch
            v-model="batchTransferDialog.form.requireApproval"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchTransferDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitBatchTransfer" :loading="batchTransferDialog.loading">
          提交申请
        </el-button>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approveDialog.visible"
      :title="approveDialog.title"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="approveDialog.form" label-width="100px">
        <el-form-item label="审批结果">
          <el-tag :type="approveDialog.action === 'approve' ? 'success' : 'danger'" size="large">
            {{ approveDialog.action === 'approve' ? '批准' : '拒绝' }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="意见分类" v-if="approveDialog.action === 'reject'">
          <el-select v-model="approveDialog.form.category" placeholder="请选择拒绝原因分类">
            <el-option label="客户信息不完整" value="incomplete_info" />
            <el-option label="转移理由不充分" value="insufficient_reason" />
            <el-option label="目标负责人不合适" value="inappropriate_target" />
            <el-option label="重复申请" value="duplicate_request" />
            <el-option label="其他原因" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="快速模板" v-if="approveDialog.action === 'reject'">
          <el-select 
            v-model="approveDialog.form.template" 
            placeholder="选择快速模板"
            @change="handleTemplateChange"
            clearable
          >
            <el-option label="客户信息缺失，请补充完整后重新申请" value="missing_info" />
            <el-option label="转移理由不够充分，建议重新评估" value="insufficient_reason" />
            <el-option label="目标负责人不符合要求，请重新选择" value="invalid_target" />
            <el-option label="该客户近期已有转移申请，请勿重复申请" value="duplicate" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="审批备注">
          <el-input
            v-model="approveDialog.form.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入审批备注（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialog.visible = false">取消</el-button>
        <el-button 
          :type="approveDialog.action === 'approve' ? 'success' : 'danger'" 
          @click="handleSubmitApproval" 
          :loading="approveDialog.loading"
        >
          {{ approveDialog.action === 'approve' ? '确认批准' : '确认拒绝' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 转移详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="转移详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="detailDialog.activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="客户姓名">{{ detailDialog.data.customerName }}</el-descriptions-item>
            <el-descriptions-item label="客户电话">{{ detailDialog.data.customerPhone }}</el-descriptions-item>
            <el-descriptions-item label="原负责人">{{ detailDialog.data.fromUserName }}</el-descriptions-item>
            <el-descriptions-item label="目标负责人">{{ detailDialog.data.toUserName }}</el-descriptions-item>
            <el-descriptions-item label="转移状态">
              <el-tag :type="getTransferStatusType(detailDialog.data.transferStatus)">
                {{ getTransferStatusLabel(detailDialog.data.transferStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ detailDialog.data.applyTime }}</el-descriptions-item>
            <el-descriptions-item label="申请人">{{ detailDialog.data.applicantName }}</el-descriptions-item>
            <el-descriptions-item label="申请原因">{{ detailDialog.data.applyReason }}</el-descriptions-item>
            <el-descriptions-item label="审批人" v-if="detailDialog.data.approverName">{{ detailDialog.data.approverName }}</el-descriptions-item>
            <el-descriptions-item label="审批时间" v-if="detailDialog.data.approveTime">{{ detailDialog.data.approveTime }}</el-descriptions-item>
            <el-descriptions-item label="审批备注" :span="2" v-if="detailDialog.data.approveRemark">{{ detailDialog.data.approveRemark }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        
        <el-tab-pane label="审批流程" name="timeline">
          <el-timeline>
            <el-timeline-item
              :timestamp="detailDialog.data.applyTime"
              placement="top"
              type="primary"
              icon="Clock"
            >
              <el-card>
                <h4>提交转移申请</h4>
                <p>申请人：{{ detailDialog.data.applicantName }}</p>
                <p>申请原因：{{ detailDialog.data.applyReason }}</p>
              </el-card>
            </el-timeline-item>
            
            <el-timeline-item
              v-if="detailDialog.data.approveTime"
              :timestamp="detailDialog.data.approveTime"
              placement="top"
              :type="detailDialog.data.transferStatus === 'approved' ? 'success' : 'danger'"
              :icon="detailDialog.data.transferStatus === 'approved' ? 'CircleCheck' : 'CircleClose'"
            >
              <el-card>
                <h4>{{ detailDialog.data.transferStatus === 'approved' ? '审批通过' : '审批拒绝' }}</h4>
                <p>审批人：{{ detailDialog.data.approverName }}</p>
                <p v-if="detailDialog.data.approveRemark">审批备注：{{ detailDialog.data.approveRemark }}</p>
              </el-card>
            </el-timeline-item>
            
            <el-timeline-item
              v-if="detailDialog.data.transferStatus === 'approved' && detailDialog.data.completeTime"
              :timestamp="detailDialog.data.completeTime"
              placement="top"
              type="success"
              icon="Check"
            >
              <el-card>
                <h4>转移完成</h4>
                <p>客户已成功转移至 {{ detailDialog.data.toUserName }}</p>
              </el-card>
            </el-timeline-item>
            
            <el-timeline-item
              v-if="detailDialog.data.transferStatus === 'pending'"
              placement="top"
              type="info"
              icon="MoreFilled"
            >
              <el-card>
                <h4>等待审批</h4>
                <p>转移申请正在等待审批人处理</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
        
        <el-tab-pane label="转移历史" name="history" v-if="detailDialog.data.transferHistory && detailDialog.data.transferHistory.length > 0">
          <el-table :data="detailDialog.data.transferHistory" border style="width: 100%">
            <el-table-column prop="fromUserName" label="原负责人" width="120" />
            <el-table-column prop="toUserName" label="目标负责人" width="120" />
            <el-table-column prop="transferTime" label="转移时间" width="160" />
            <el-table-column prop="reason" label="转移原因" min-width="200" />
            <el-table-column prop="operator" label="操作人" width="100" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTransferList,
  approveTransfer,
  rejectTransfer,
  batchApproveTransfer,
  batchRejectTransfer,
  exportTransfers,
  deleteTransfer,
  batchTransferCustomer,
  getTransferTrend,
  getUserList
} from '@/api/crm'
import { useUserStore } from '@/stores/user'
import { hasPermission } from '@/utils/permission'
import { Clock, CircleCheck, CircleClose, MoreFilled, Check } from '@element-plus/icons-vue'

// 用户store和权限
const userStore = useUserStore()

// 权限计算属性
const canApprove = computed(() => hasPermission('crm:transfer:approve'))
const canReject = computed(() => hasPermission('crm:transfer:reject'))
const canBatchApprove = computed(() => hasPermission('crm:transfer:batch:approve'))
const canBatchReject = computed(() => hasPermission('crm:transfer:batch:reject'))
const canExport = computed(() => hasPermission('crm:transfer:export'))
const canDelete = computed(() => hasPermission('crm:transfer:delete'))
const canTransfer = computed(() => hasPermission('crm:transfer:create'))
const trendChartRef = ref<HTMLElement>()
const trendData = ref<any[]>([])
let trendChart: any = null
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 统计数据
const statistics = reactive({
  pending: 0,
  approved: 0,
  rejected: 0
})

// 搜索表单
const searchForm = reactive({
  customerName: '',
  transferStatus: '',
  applicantName: '',
  applyDateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const userOptions = ref([])
const customerOptions = ref([])

// 加载状态管理
const batchApproveLoading = ref(false)
const batchRejectLoading = ref(false)
const exportLoading = ref(false)
const customerLoading = ref(false)

// 表格高度计算
const tableHeight = computed(() => {
  const windowHeight = window.innerHeight
  return windowHeight - 350
})

// 对话框状态
const batchTransferDialog = reactive({
  visible: false,
  loading: false,
  form: {
    customerIds: [],
    targetUserId: null,
    remark: '',
    requireApproval: true
  .trend-chart-card {
    margin-bottom: 20px;
    
    .el-card__header {
      padding: 15px 20px;
      font-weight: 500;
    }
    
    .el-card__body {
      padding: 20px;
    }
  // 导出相关样式
  .export-dialog {
    .el-message-box__content {
      padding: 20px;
    }
    
    .el-radio-group {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .el-radio {
        margin-right: 0;
        height: 32px;
        line-height: 32px;
      }
    }
  })

const approveDialog = reactive({
  visible: false,
  loading: false,
  title: '审批转移申请',
  action: 'approve',
  form: {
    transferId: null,
    category: '',
    template: '',
    remark: ''
  }
})
// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: {},
  activeTab: 'basic'
})

// 获取转移状态标签
const getTransferStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    pending: '待审批',
    approved: '已批准',
    rejected: '已拒绝',
    completed: '已完成'
  }
  return labels[status] || status
}

const getTransferStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    completed: 'info'
  }
  return types[status] || 'info'
}

// 获取转移记录列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getTransferList(params)
    tableData.value = res.rows
    pagination.total = res.total
    
    // 更新统计数据
    updateStatistics(res.rows)
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取转移记录失败'
    ElMessage.error(errorMessage)
    console.error('获取转移记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStatistics = (data: any[]) => {
  statistics.pending = data.filter(item => item.transferStatus === 'pending').length
  statistics.approved = data.filter(item => item.transferStatus === 'approved').length
  statistics.rejected = data.filter(item => item.transferStatus === 'rejected').length
}

// 获取趋势数据
const fetchTrendData = async () => {
  try {
    const response = await getTransferTrend()
    trendData.value = response.data || []
    initTrendChart()
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    trendData.value = []
  }
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value || trendData.value.length === 0) return
  
  if (trendChart) {
    trendChart.dispose()
  }
  
  // 动态导入ECharts
  import('echarts').then(({ init }) => {
    trendChart = init(trendChartRef.value)
    
    const option = {
      title: {
        text: '客户转移审批趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['申请数量', '批准数量', '拒绝数量'],
        bottom: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: trendData.value.map(item => item.date),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '数量'
      },
      series: [
        {
          name: '申请数量',
          type: 'line',
          data: trendData.value.map(item => item.total),
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '批准数量',
          type: 'line',
          data: trendData.value.map(item => item.approved),
          smooth: true,
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '拒绝数量',
          type: 'line',
          data: trendData.value.map(item => item.rejected),
          smooth: true,
          itemStyle: {
            color: '#F56C6C'
          }
        }
      ]
    }
    
    trendChart.setOption(option)
    
    // 响应式处理
    window.addEventListener('resize', () => {
      trendChart?.resize()
    })
  }).catch(error => {
    console.error('加载ECharts失败:', error)
  })
}
  try {
    const res = await getUserList()
    userOptions.value = res
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取用户列表失败'
    ElMessage.error(errorMessage)
    console.error('获取用户列表失败:', error)
  }
}

// 搜索客户
const searchCustomers = async (keyword: string) => {
  if (!keyword) return
  customerLoading.value = true
  try {
    const res = await getCustomerList({ 
      customerName: keyword,
      pageSize: 20
    })
    customerOptions.value = res.rows
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '搜索客户失败'
    ElMessage.error(errorMessage)
    console.error('搜索客户失败:', error)
  } finally {
    customerLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    transferStatus: '',
    applicantName: '',
    applyDateRange: []
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 选择行
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
  
  // 智能提示：如果有混合状态的记录，提醒用户只处理待审批的
  if (rows.length > 0) {
    const pendingCount = rows.filter(row => row.transferStatus === 'pending').length
    const otherCount = rows.length - pendingCount
    
    if (otherCount > 0 && pendingCount > 0) {
      ElMessage.info(`已选择 ${rows.length} 条记录，其中 ${pendingCount} 条为待审批状态，批量操作将只处理待审批记录`)
    } else if (otherCount > 0 && pendingCount === 0) {
      ElMessage.warning('当前选择的记录中没有待审批的记录，批量操作将无法执行')
    }
  }
}

// 批量转移
const handleBatchTransfer = () => {
  batchTransferDialog.visible = true
  batchTransferDialog.form = {
    customerIds: [],
    targetUserId: null,
    remark: '',
    requireApproval: true
  }
}

// 提交批量转移
const handleSubmitBatchTransfer = async () => {
  if (!batchTransferDialog.form.customerIds.length) {
    ElMessage.warning('请选择要转移的客户')
    return
  }
  if (!batchTransferDialog.form.targetUserId) {
    ElMessage.warning('请选择目标用户')
    return
  }
  
  batchTransferDialog.loading = true
  try {
    // 这里调用批量转移API
    await batchTransferCustomer(batchTransferDialog.form)
    ElMessage.success('批量转移申请已提交')
    batchTransferDialog.visible = false
    fetchData()
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '批量转移失败'
    ElMessage.error(errorMessage)
    console.error('批量转移失败:', error)
  } finally {
    batchTransferDialog.loading = false
  }
}

// 批准转移
const handleApprove = (row: any) => {
  approveDialog.action = 'approve'
  approveDialog.title = '批准转移申请'
  approveDialog.form.transferId = row.id
  approveDialog.form.remark = ''
  approveDialog.visible = true
}

// 拒绝转移
const handleReject = (row: any) => {
  approveDialog.action = 'reject'
  approveDialog.title = '拒绝转移申请'
  approveDialog.form.transferId = row.id
  approveDialog.form.remark = ''
  approveDialog.visible = true
}

// 提交审批
const handleSubmitApproval = async () => {
  // 权限检查
  if (!canApprove.value && approveDialog.action === 'approve') {
    ElMessage.error('您没有审批通过的权限')
    return
  }
  if (!canReject.value && approveDialog.action === 'reject') {
    ElMessage.error('您没有审批拒绝的权限')
    return
  }
  
  if (!approveDialog.form.remark.trim() && approveDialog.action === 'reject' && !approveDialog.form.category) {
    ElMessage.warning('请填写拒绝原因分类或审批备注')
    return
  }
  
  approveDialog.loading = true
  try {
    const params = {
      id: approveDialog.form.transferId,
      status: approveDialog.action === 'approve' ? 'approved' : 'rejected',
      remark: approveDialog.form.remark,
      category: approveDialog.form.category,
      template: approveDialog.form.template
    }
    
    if (approveDialog.action === 'approve') {
      await approveTransfer(params)
      ElMessage.success('转移申请已批准')
    } else {
      await rejectTransfer(params)
      ElMessage.success('转移申请已拒绝')
    }
    
    approveDialog.visible = false
    fetchData()
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '审批失败'
    ElMessage.error(errorMessage)
    console.error('审批失败:', error)
  } finally {
    approveDialog.loading = false
  }
}

// 批量批准
const handleBatchApprove = async () => {
  if (selectedRows.value.length === 0) return
  
  const pendingRows = selectedRows.value.filter(row => row.transferStatus === 'pending')
  if (pendingRows.length === 0) {
    ElMessage.warning('请选择待审批的记录')
    return
  }
  
  batchApproveLoading.value = true
  try {
    await ElMessageBox.confirm(
      <div style="text-align: center;">
        <p style="font-size: 16px; margin-bottom: 10px;">确定要批量批准这 <strong style="color: #67c23a;">${pendingRows.length}</strong> 条转移申请吗？</p>
        <p style="color: #909399; font-size: 14px;">此操作将同时批准所有选中的待审批申请</p>
      </div>,
      '批量批准确认',
      {
        confirmButtonText: '确定批准',
        cancelButtonText: '取消',
        type: 'success',
        dangerouslyUseHTMLString: true
      }
    )
    
    // 显示进度条
    const progressInstance = ElMessage({
      message: '正在批量处理中...',
      duration: 0,
      icon: 'Loading'
    })
    
    const ids = pendingRows.map(row => row.id)
    const response = await batchApproveTransfer(ids)
    
    // 关闭进度条
    progressInstance.close()
    
    // 显示详细结果
    const successCount = response?.data?.successCount || pendingRows.length
    const failedCount = response?.data?.failedCount || 0
    
    if (failedCount > 0) {
      ElMessage({
        message: `批量处理完成！成功批准 ${successCount} 条，失败 ${failedCount} 条`,
        type: successCount > 0 ? 'warning' : 'error',
        duration: 5000,
        showClose: true
      })
    } else {
      ElMessage.success(`成功批准 ${successCount} 条转移申请`)
    }
    
    // 清空选择
    selectedRows.value = []
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      const errorMessage = error?.response?.data?.message || error?.message || '批量批准失败'
      ElMessage.error(errorMessage)
      console.error('批量批准失败:', error)
    }
  } finally {
    batchApproveLoading.value = false
  }
}

// 批量拒绝
const handleBatchReject = async () => {
  if (selectedRows.value.length === 0) return
  
  const pendingRows = selectedRows.value.filter(row => row.transferStatus === 'pending')
  if (pendingRows.length === 0) {
    ElMessage.warning('请选择待审批的记录')
    return
  }
  
  batchRejectLoading.value = true
  try {
    await ElMessageBox.confirm(
      `<div style="text-align: center;">
        <p style="font-size: 16px; margin-bottom: 10px;">确定要批量拒绝这 <strong style="color: #f56c6c;">${pendingRows.length}</strong> 条转移申请吗？</p>
        <p style="color: #909399; font-size: 14px;">此操作将同时拒绝所有选中的待审批申请</p>
      </div>`,
      '批量拒绝确认',
      {
        confirmButtonText: '确定拒绝',
        cancelButtonText: '取消',
        type: 'error',
        dangerouslyUseHTMLString: true
      }
    )
    
    // 显示进度条
    const progressInstance = ElMessage({
      message: '正在批量处理中...',
      duration: 0,
      icon: 'Loading'
    })
    
    const ids = pendingRows.map(row => row.id)
    const response = await batchRejectTransfer(ids)
    
    // 关闭进度条
    progressInstance.close()
    
    // 显示详细结果
    const successCount = response?.data?.successCount || pendingRows.length
    const failedCount = response?.data?.failedCount || 0
    
    if (failedCount > 0) {
      ElMessage({
        message: `批量处理完成！成功拒绝 ${successCount} 条，失败 ${failedCount} 条`,
        type: successCount > 0 ? 'warning' : 'error',
        duration: 5000,
        showClose: true
      })
    } else {
      ElMessage.success(`成功拒绝 ${successCount} 条转移申请`)
    }
    
    // 清空选择
    selectedRows.value = []
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      const errorMessage = error?.response?.data?.message || error?.message || '批量拒绝失败'
      ElMessage.error(errorMessage)
      console.error('批量拒绝失败:', error)
    }
  } finally {
    batchRejectLoading.value = false
  }
}

// 查看详情
const handleView = (row: any) => {
  detailDialog.data = row
  detailDialog.visible = true
}

// 处理模板变更
const handleTemplateChange = (value: string) => {
  const templates = {
    missing_info: '客户信息缺失，请补充完整后重新申请',
    insufficient_reason: '转移理由不够充分，建议重新评估',
    invalid_target: '目标负责人不符合要求，请重新选择',
    duplicate: '该客户近期已有转移申请，请勿重复申请'
  }
  if (value && templates[value]) {
    approveDialog.form.remark = templates[value]
  }
}

// 删除记录
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该转移记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteTransfer(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      const errorMessage = error?.response?.data?.message || error?.message || '删除失败'
      ElMessage.error(errorMessage)
      console.error('删除失败:', error)
    }
  }
}

// 导出记录
const handleExport = async () => {
  if (!canExport.value) {
    ElMessage.error('您没有数据导出的权限')
    return
  }
  
  // 显示导出格式选择对话框
  ElMessageBox.confirm(
    '<div style="margin-bottom: 10px;">请选择导出格式：</div>' +
    '<el-radio-group v-model="exportFormat">' +
    '<el-radio label="excel">Excel 格式 (.xlsx)</el-radio><br/>' +
    '<el-radio label="csv">CSV 格式 (.csv)</el-radio><br/>' +
    '<el-radio label="pdf">PDF 格式 (.pdf)</el-radio>' +
    '</el-radio-group>',
    '数据导出',
    {
      confirmButtonText: '导出',
      cancelButtonText: '取消',
      dangerouslyUseHTMLString: true,
      distinguishCancelAndClose: true,
      customClass: 'export-dialog',
      callback: async (action: string, instance: any) => {
        if (action === 'confirm') {
          const format = instance.$refs?.radioGroup?.modelValue || 'excel'
          await performExport(format)
        }
      }
    }
  )
}

// 执行导出
const performExport = async (format: string) => {
  exportLoading.value = true
  
  try {
    // 构建导出参数
    const exportParams = {
      ...searchForm,
      format: format,
      pageNum: 1,
      pageSize: 10000 // 导出所有数据，不受分页限制
    }
    
    // 调用导出API
    const response = await exportTransfers(exportParams)
    
    // 处理文件下载
    const blob = new Blob([response.data], {
      type: format === 'pdf' ? 'application/pdf' : 
            format === 'csv' ? 'text/csv;charset=utf-8;' : 
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名
    const timestamp = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/[/:]/g, '-')
    
    const extension = format === 'pdf' ? 'pdf' : format === 'csv' ? 'csv' : 'xlsx'
    link.download = `客户转移审批数据_${timestamp}.${extension}`
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success(`数据导出成功，格式：${format.toUpperCase()}`)
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('数据导出失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchData()
  fetchUserOptions()
  fetchTrendData()
})
</script>

<style scoped lang="scss">
.customer-transfer {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  // 状态统计卡片样式
  .status-statistics {
    margin-bottom: 20px;
    
    .status-card {
      border-radius: 8px;
      transition: all 0.3s ease;
      
      &.pending {
        background: linear-gradient(135deg, #FFA726 0%, #FF9800 100%);
        color: white;
      }
      
      &.approved {
        background: linear-gradient(135deg, #66BB6A 0%, #4CAF50 100%);
        color: white;
      }
      
      &.rejected {
        background: linear-gradient(135deg, #EF5350 0%, #F44336 100%);
        color: white;
      }
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
      
      .status-card-content {
        display: flex;
        align-items: center;
        padding: 20px;
        
        .status-icon {
          font-size: 32px;
          margin-right: 16px;
          opacity: 0.9;
        }
        
        .status-info {
          flex: 1;
          
          .status-number {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 4px;
          }
          
          .status-label {
            font-size: 14px;
            opacity: 0.9;
          }
        }
      }
    }
  }

  .search-form {
    margin-bottom: 20px;
  }

  .batch-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 响应式设计
  @media screen and (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .status-statistics {
      .el-col {
        margin-bottom: 10px;
      }
    }

    .batch-actions {
      justify-content: center;
    }

    .pagination {
      justify-content: center;
    }
  }

  @media screen and (max-width: 480px) {
    .search-form {
      .el-form-item {
        margin-bottom: 10px;
      }
    }

    .batch-actions {
      .el-button {
        margin-bottom: 5px;
      }
    }
  }
}
</style>